package com.ligg.apicommon.controller;

import com.ligg.common.constants.Constant;
import com.ligg.common.service.FileService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Tag(name = "图片接口")
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class imageController {

    @Value("${file.image.base-path}")
    private String IMAGE_PATH;

    private final FileService fileService;

    /**
     * 获取图片资源
     * @param imageName 图片名称
     * @param date      图片日期
     * @return 图片文件流
     */
    @GetMapping("/image/{path}/{date}/{imageName}")
    public ResponseEntity<StreamingResponseBody> getImageStream(
            @PathVariable String date,
            @PathVariable String path,
            @PathVariable String imageName
    ) {
        Path imagePath = Paths.get(IMAGE_PATH, path, date, imageName);
        if (!Files.exists(imagePath)) {
            return ResponseEntity.notFound().build();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg");
        return ResponseEntity.ok().headers(headers).body(fileService.getImageInputStream(path, date, imageName));
    }

    /**
     * 获取多个类型图片资源
     *
     * @param date      图片日期
     * @param imageName 图片名称
     * @return 图片文件流
     */
    @GetMapping("/image/{type}/{path}/{date}/{imageName}")
    public ResponseEntity<StreamingResponseBody> getImageStream(
            @PathVariable String type,
            @PathVariable String path,
            @PathVariable String date,
            @PathVariable String imageName
    ) {

        Path imagePath = Paths.get(IMAGE_PATH, path, date, imageName);
        if (!Files.exists(imagePath)) {
            return ResponseEntity.notFound().build();
        }

        StreamingResponseBody imageInputStream = fileService.getImageInputStream(path, type, date, imageName);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg");

        return ResponseEntity.ok().headers(headers).body(imageInputStream);
    }

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("image") MultipartFile imageFile) {
        return fileService.minioFileUpload(imageFile, Constant.AVATAR_FILE_PATH);
    }
}
